package com.ikunikun.task;

import com.ikunikun.entity.Orders;
import com.ikunikun.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Component
public class ServiceTask {

	@Resource
	private OrderMapper orderMapper;

	/**
	 * 超时订单处理
	 */
	// 每分钟处理一次
	@Scheduled(cron = "0 * * * * ?")
	public void processTimeoutOrder(){
		log.info("定时处理超时订单：{}", LocalDateTime.now());
		// 查询待付款，且超时15分钟
		LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
		List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.PENDING_PAYMENT, time);
		if (orders.isEmpty()){
			return;
		}
		for (Orders order : orders) {
			order.setStatus(Orders.CANCELLED);
			order.setCancelReason("订单超时，自动取消");
			order.setCancelTime(LocalDateTime.now());
			orderMapper.update(order);
		}
	}

	/**
	 * 长时间未签收订单处理
	 */
	@Scheduled(cron = "0 0 2 * * ?")
	public void processDeliveryOrder(){
		log.info("定时处理长时间未签收订单：{}", LocalDateTime.now());
		LocalDateTime time = LocalDateTime.now().plusHours(-2);
		List<Orders> orders = orderMapper.getByStatusAndOrderTimeLT(Orders.DELIVERY_IN_PROGRESS, time);
		if (orders.isEmpty()){
			return;
		}
		for (Orders order : orders) {
			order.setStatus(Orders.COMPLETED);
			orderMapper.update(order);
		}
	}
}
